package com.ehsy.wos.common.utils.sign;

import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author YanZhen_Li
 * @version 1.0
 * @create 2023/9/20 17:14
 */
@Slf4j
public class Md5StringUtils {
    public static String md5(String str) {
        if (str == null){
            log.error("md5() <== The md5 input cannot be null.");
            log.error("md5() <== md5的入参不能为空。");
            return null;
        }
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] hashBytes = md.digest(str.getBytes());

            // Convert the byte array to hexadecimal representation
            StringBuilder hexString = new StringBuilder();
            for (byte hashByte : hashBytes) {
                String hex = Integer.toHexString(0xFF & hashByte);
                if (hex.length() == 1) {
                    hexString.append('0');  // Padding for single digit
                }
                hexString.append(hex);
            }

            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            log.error("md5() <==> The md5 operation is abnormal. md5运算发生异常：", e);
            return null;
        }
    }

    public static String md5(String str1,Object str2){
        return md5(str1+"&"+str2);
    }

    public static String md5Digest(String str){
        return DigestUtils.md5DigestAsHex(str.getBytes());
    }

    public static String md5Digest(String str1,Object str2){
        return md5Digest(str1+"&"+str2);
    }

}
